import React, {useState, useEffect} from 'react';
import styles from '../../styles/RoomTag.module.css'
import Image from 'next/image'
import roomPic from '../../public/image/room.png'

export default function RoomTag(props) {
    const {roomName, lastMsg,msgTime, onClick, isSelect,onLeaveCallback} = props;

    console.log(msgTime)
    const [showMenu, setShowMenu] = useState(false)
    const [menuX, setMenuX] = useState(0)
    const [menuY, setMenuY] = useState(0)
    useEffect(() => {
        document.addEventListener('click',hideMenu)
        return ()=>document.removeEventListener('click',hideMenu)
    })

    const hideMenu = () => {
        setShowMenu(false)
    }

    const tagOnClick = () => {
        onClick(roomName)
    }

    const onRightClick = e => {
        e.preventDefault()
        setMenuX(e.clientX)
        setMenuY(e.clientY)
        setShowMenu(true)
    }

    const position = {top: menuY, left: menuX}

    return (
        <>
            <div className={`${styles.flex} ${isSelect ? styles.tagSelected : styles.tagNotSelect}`}
                 onClick={tagOnClick}
                 onContextMenu={onRightClick}>
                <div>
                    <Image src={roomPic} width={30} height={40}/>
                </div>
                <div>
                    <div className={styles.title}>{roomName}</div>
                    <div className={styles.msg}>{lastMsg}</div>
                </div>
                <div className={styles.time}>
                  {msgTime}
                </div>
            </div>

            {
                showMenu ? (<div className={styles.menu} style={position} onClick={()=>onLeaveCallback(roomName)}>退出房间</div>) : null
            }
        </>
    )
}
